package com.ibiaoke.boss.controller;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.ibiaoke.common.base.BaseController;
import com.ibiaoke.common.exception.ServiceException;
import com.ibiaoke.customer.consts.PayTypeConst;
import com.ibiaoke.customer.service.TradeRecorderService;
import com.ibiaoke.order.dao.XcxOrderDao;
import com.ibiaoke.order.entity.XcxOrder;
import com.ibiaoke.order.service.XcxOrderService;
import com.ibiaoke.pay.AppWXPayConfigImpl;
import com.ibiaoke.pay.WXPayConfigImpl;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Objects;

import static java.util.stream.Collectors.joining;

@Controller
public class XcxPayNotifyController extends BaseController {

    private Logger logger = Logger.getLogger(this.getClass().getName());

    @Autowired
    private XcxOrderDao xcxOrderDao;

    @Autowired
    private XcxOrderService xcxOrderService;

    @Autowired
    private TradeRecorderService tradeRecorderService;

    @RequestMapping("/XcxPtPayNotify/{businessType}")
    public void xcxPtPayNotify(@PathVariable String businessType, HttpServletRequest request, HttpServletResponse response) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
            String dataXml = br.lines().collect(joining());
            Map<String, String> dataMap = WXPayUtil.xmlToMap(dataXml);
            WXPay wxPay;
            if (businessType.equals("XCX_PAY_ORDER") || businessType.equals("PAY_DEPOSIT")) {
                wxPay = new WXPay(new WXPayConfigImpl());
            }else {
                wxPay = new WXPay(new AppWXPayConfigImpl());
            }
            //判断是否是微信响应
            boolean valid = wxPay.isResponseSignatureValid(dataMap);
            if(valid){
                if(Objects.equals(dataMap.get("return_code"), WXPayConstants.SUCCESS)){
                    if(Objects.equals(dataMap.get("result_code"), WXPayConstants.SUCCESS)){
                        String out_trade_no = dataMap.get("out_trade_no");
                        String transaction_id = dataMap.get("transaction_id");
                        int result = 0;
                        //微信回调
                        if (Objects.equals(businessType, "XCX_PAY_ORDER")) {
                            logger.info("小程序系统交易成功，开始执行回调业务");
                            XcxOrder xcxOrder = xcxOrderDao.getOrderByOrderCode(out_trade_no);
                            if(xcxOrder.getOrderType() == 0){//单买
                                System.out.println("                    进入单独下单回调方法");
                                //更改 订单  1支付时间 2更新时间 3状态为 4售出数量 5分店铺商品库存
                                xcxOrderService.updateOrderStatusByOnly(xcxOrder);
                                result = xcxOrderDao.upPtOrderTransaction(xcxOrder.getOrderId(),transaction_id);
                            }else if(xcxOrder.getOrderType() == 3){//快捷支付
                                System.out.println("                    进入快捷支付回调方法");
                                //更改 订单 1支付时间 2更新时间 3状态  4微信交易记录号
                                xcxOrderDao.upPtOrderTransaction(xcxOrder.getOrderId(),transaction_id);
                                xcxOrderDao.updatePayTimeAndUpdateTime(xcxOrder);
                                result = xcxOrderDao.upPtOrderStatus(xcxOrder.getOrderId(),3);
                            } else{//拼团或参团
                                System.out.println("                    进入拼团回调方法");
                                //拼团、参团回调
                                xcxOrderService.updateOrderStatus(xcxOrder);
                                result = xcxOrderDao.upPtOrderTransaction(xcxOrder.getOrderId(),transaction_id);
                            }
                        }
                        if (Objects.equals(businessType, "PAY_DEPOSIT")) {
                            logger.info("小程序系统充值交易成功，开始执行回调业务");
                            result=tradeRecorderService.depositChargeSuccess(out_trade_no, PayTypeConst.WECAHT,transaction_id);
                        }
                        if(result>0) {
                            PrintWriter writer = response.getWriter();
                            writer.print("<xml><return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg></xml>");
                            writer.close();
                        }
                    }
                }else{
                    dataMap.get("return_msg");
                }
            }
        } catch (Exception e) {
            throw new ServiceException("微信支付回调异常",e);
        }
    }
}
